package org.zebra.web.annotation.version;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.zebra.common.exception.ResultException;
import org.zebra.common.exception.StatusCode;

import javax.servlet.http.HttpServletRequest;

/**
 * 接口版本控制
 *
 * @author zhanghongbin
 */
@Data
@AllArgsConstructor
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {

    private ApiVersionVO apiVersionVO;

    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition apiVersionRequestCondition) {
        // 选择版本最大的接口
        //        return apiVersionVO.compareTo(apiVersionRequestCondition.getApiVersionVO()) >= 0
        //                ? new ApiVersionRequestCondition(apiVersionVO)
        //                : new ApiVersionRequestCondition(apiVersionRequestCondition.getApiVersionVO());
        return apiVersionRequestCondition;
    }

    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
        // 通过uri匹配版本号
        ApiVersionVO item = ApiVersionConverter.parse(request.getRequestURI());
        if (item == null) throw new ResultException(StatusCode.NOT_FOUND.getCode(), StatusCode.NOT_FOUND.getMsg());
        if (this.apiVersionVO.getApiVersion().deprecated()) {
            throw new ResultException(
                    StatusCode.API_VERSION_DEPRECATED.getCode(), StatusCode.API_VERSION_DEPRECATED.getMsg());
        }
        // 获取所有小于等于版本的接口
        int n = item.compareTo(this.apiVersionVO);
        if (n >= 0) {
            return this;
        }
        return null;
    }

    /**
     * 获取最大版本对应的接口
     *
     * @param other 条件对象
     * @param httpServletRequest http request
     * @return 取版本号最大的
     */
    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest httpServletRequest) {
        return other.getApiVersionVO().compareTo(this.apiVersionVO);
    }
}
